import { DataTypes, Model, Op } from 'sequelize';
import sequelize from '../utils/database';
import { User } from './User';

export interface UserAddressAttributes {
  id?: number;
  userId: number;
  receiverName: string;
  receiverPhone: string;
  province: string;
  city: string;
  district: string;
  address: string;
  postalCode?: string;
  isDefault?: 0 | 1; // 0-否，1-是
  createdAt?: Date;
  updatedAt?: Date;
}

export class UserAddress extends Model<UserAddressAttributes> implements UserAddressAttributes {
  public id!: number;
  public userId!: number;
  public receiverName!: string;
  public receiverPhone!: string;
  public province!: string;
  public city!: string;
  public district!: string;
  public address!: string;
  public postalCode?: string;
  public isDefault!: 0 | 1;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  // 实例方法
  public getFullAddress(): string {
    return `${this.province}${this.city}${this.district}${this.address}`;
  }

  public getIsDefaultText(): string {
    return this.isDefault === 1 ? '默认地址' : '普通地址';
  }
}

UserAddress.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '用户ID',
      field: 'user_id',
      references: {
        model: User,
        key: 'id',
      },
    },
    receiverName: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: '收货人姓名',
      field: 'receiver_name',
      validate: {
        len: [1, 50],
        notEmpty: true,
      },
    },
    receiverPhone: {
      type: DataTypes.STRING(20),
      allowNull: false,
      comment: '收货人电话',
      field: 'receiver_phone',
      validate: {
        is: /^1[3-9]\d{9}$/,
      },
    },
    province: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: '省份',
      validate: {
        len: [1, 50],
        notEmpty: true,
      },
    },
    city: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: '城市',
      validate: {
        len: [1, 50],
        notEmpty: true,
      },
    },
    district: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: '区县',
      validate: {
        len: [1, 50],
        notEmpty: true,
      },
    },
    address: {
      type: DataTypes.STRING(200),
      allowNull: false,
      comment: '详细地址',
      validate: {
        len: [1, 200],
        notEmpty: true,
      },
    },
    postalCode: {
      type: DataTypes.STRING(10),
      allowNull: true,
      comment: '邮政编码',
      field: 'postal_code',
      validate: {
        is: /^\d{6}$/,
      },
    },
    isDefault: {
      type: DataTypes.TINYINT,
      defaultValue: 0,
      comment: '是否默认地址：0-否，1-是',
      field: 'is_default',
      validate: {
        isIn: [[0, 1]],
      },
    },
  },
  {
    sequelize,
    modelName: 'UserAddress',
    tableName: 'user_addresses',
    timestamps: true,
    underscored: true,
    indexes: [
      {
        fields: ['user_id'],
      },
      {
        fields: ['is_default'],
      },
    ],
    hooks: {
      beforeCreate: async (address: UserAddress) => {
        // 如果设置为默认地址，将该用户的其他地址设为非默认
        if (address.isDefault === 1) {
          await UserAddress.update(
            { isDefault: 0 },
            { where: { userId: address.userId } }
          );
        }
      },
      beforeUpdate: async (address: UserAddress) => {
        // 如果设置为默认地址，将该用户的其他地址设为非默认
        if (address.isDefault === 1) {
          await UserAddress.update(
            { isDefault: 0 },
            { where: { userId: address.userId, id: { [Op.ne]: address.id } } }
          );
        }
      },
    },
  }
);

// 定义关联关系
User.hasMany(UserAddress, { foreignKey: 'userId', as: 'addresses' });
UserAddress.belongsTo(User, { foreignKey: 'userId', as: 'user' });